# -*- coding: utf-8 -*-

import logging
import os
from logging.handlers import RotatingFileHandler

from flask.logging import default_handler

from domain.singleton import singleton

BASE_DIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))

LOG_PATH = os.path.join(BASE_DIR, 'logs')

LOG_PATH_ERROR = os.path.join(LOG_PATH, 'error.log')
LOG_PATH_INFO = os.path.join(LOG_PATH, 'info.log')
LOG_PATH_ALL = os.path.join(LOG_PATH, 'all.log')

# 日志文件最大 100MB
LOG_FILE_MAX_BYTES = 100 * 1024 * 1024
# 轮转数量是 10 个
LOG_FILE_BACKUP_COUNT = 10
LOG_FORMAT = '%(asctime)s[%(levelname)s][%(filename)s:%(module)s:%(funcName)s:%(lineno)d]: %(message)s'


@singleton
class Logger(object):
    level_relations = {
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'error': logging.ERROR,
        'crit': logging.CRITICAL
    }

    def __init__(self, filename=LOG_PATH_ALL, level='info', when='D', backup_count=LOG_FILE_BACKUP_COUNT,
                 fmt=LOG_FORMAT):

        self.logger = logging.getLogger(filename)
        format_str = logging.Formatter(fmt)  # 设置日志格式
        self.logger.setLevel(self.level_relations.get(level))  # 设置日志级别

        # 向控制台输出日志
        self.stream_handler = logging.StreamHandler()
        self.stream_handler.setFormatter(format_str)
        self.logger.addHandler(self.stream_handler)

        if not os.path.exists(LOG_PATH):
            os.mkdir(LOG_PATH)
        if not os.path.isfile(LOG_PATH_ALL):  # 无文件时创建
            fd = open(LOG_PATH_ALL, mode="w", encoding="utf-8")
            fd.close()
        if not os.path.isfile(LOG_PATH_ERROR):  # 无文件时创建
            fd = open(LOG_PATH_ERROR, mode="w", encoding="utf-8")
            fd.close()
        if not os.path.isfile(LOG_PATH_INFO):  # 无文件时创建
            fd = open(LOG_PATH_INFO, mode="w", encoding="utf-8")
            fd.close()

        # 日志按文件大小写入文件
        # 1MB = 1024 * 1024 bytes
        # 这里设置文件的大小为500MB
        self.file_handler = RotatingFileHandler(
            filename=LOG_PATH_ALL,
            mode='a',
            maxBytes=LOG_FILE_MAX_BYTES,
            backupCount=backup_count,
            encoding='utf-8'
        )
        self.file_handler.setFormatter(format_str)
        self.logger.addHandler(self.file_handler)

    def init_app(self, app):
        # 移除默认的handler
        app.logger.removeHandler(default_handler)

        app.logger.addHandler(self.file_handler)
        app.logger.addHandler(self.stream_handler)


logger = Logger().logger
